package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    ImageProperties imageProperties;

    /**
     * post  /upload/image
     */
    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile pic) throws IOException {
        /**
         * 判断文件是否为空
         */

        if (ObjectUtils.isEmpty(pic) || pic.isEmpty()) {
            return ResultVO.failed("文件不能为空的");
        }

        /**
         * 验证文件类型
         */
        String contentType = pic.getContentType();
        if (!imageProperties.getTypes().contains(contentType)) {
            String types = imageProperties.getTypes().stream()
                    .map(type -> type.substring(type.lastIndexOf("/") + 1))
                    .collect(Collectors.joining("、"));
            return ResultVO.failed("仅支持" + types + "类型的图片");
        }



        /**
         * 修改文件名称
         */
        String originalFilename = pic.getOriginalFilename();
        //jpg  png
        String suffix = FileNameUtil.getSuffix(originalFilename);
        String filename = IdUtil.simpleUUID() + StrUtil.DOT + suffix;


        /**
         * 上传目录
         */
        File uploadDir=new File(imageProperties.getLocation());
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }

        /**
         * 创建目录文件
         */
        File destFile=new File(uploadDir,filename);;

        /**
         * 上传文件
         */
        pic.transferTo(destFile);

        String path= imageProperties.getPrefix().endsWith(StrUtil.SLASH)?
                imageProperties.getPrefix()+filename:
                imageProperties.getPrefix()+StrUtil.SLASH+filename;
        return ResultVO.success(path);

    }

}
